package cn.doitedu.vueapi.flowdata;

import cn.doitedu.vueapi.pojo.tg.AdPvs;
import cn.doitedu.vueapi.service.tg.AdFlowServiceImpl;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class RealTimeDataImport {
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.ENGLISH);
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    boolean stop = false;
    Thread thread = null;
    // 位置记录文件
    FileInputStream in = null;
    FileOutputStream out = null;
    RandomAccessFile r = null;

    @Autowired
    AdFlowServiceImpl adFlowService;

    @RequestMapping("/hunter123/start")
    public String startImport() {

        thread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Pattern p2 = Pattern.compile("(.*) - - \\[(.*) +.* \"GET /.*trace=(.*) HTTP");
                    in = new FileInputStream("/www/wwwroot/pos.json");
                    byte[] buf = new byte[1024];
                    int read = in.read(buf);
                    in.close();
                    String pos = new String(buf, 0, read);

                    String[] info = pos.split("_");
                    // 日志所在位置
                    String logname = info[0].trim();
                    // 偏移量
                    Long offset = Long.valueOf(info[1].trim());

                    r = new RandomAccessFile(logname, "r");
                    r.seek(offset);
                    String line = "";
                    while (!stop) {
                        line = r.readLine();
                        if (line == null) {
                            Thread.sleep(1000);
                            continue;
                        }
                        try {
                            Matcher m = p2.matcher(line);
                            if (!m.find()) {
                                continue;
                            } else {
                                // 抽取ip
                                String ip = m.group(1);
                                // 抽取日期
                                String dt = m.group(2);
                                Date date = sdf1.parse(dt);
                                String dtStr = sdf2.format(date);

                                // 抽取跟踪码
                                String enc = m.group(3);
                                String trace = new String(Base64.decodeBase64(enc));
                                String[] split = trace.split(":");
                                Integer uid = Integer.valueOf(split[0]);
                                Integer adid = Integer.valueOf(split[1]);

                                // 插入新数据
                                System.out.println("准备插入pv记录数据...................");
                                AdPvs adPvs = new AdPvs();
                                adPvs.setUid(uid);
                                adPvs.setAdid(adid);
                                adPvs.setDt(dtStr);
                                adPvs.setIp(ip);
                                adFlowService.addPvShow(adPvs);

                                // 更新偏移量
                                offset = r.getFilePointer();
                                out = new FileOutputStream("/www/wwwroot/pos.json");
                                out.write((logname + "_" + offset).getBytes());
                                out.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        return "启动成功";
    }

    @RequestMapping("/hunter123/stop")
    public String stopImport() {
        this.stop = true;
        try{
            Thread.sleep(2000);
            thread.interrupt();
            if(in != null) {
                in.close();
            }
            if(out != null){
                out.close();
            }
            if(r != null){
                r.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return "关闭完成";
    }

}
